package cn.qingfeng.demo.transaction.springboot.declarative.transactionSimple.service.impl;

import cn.qingfeng.demo.transaction.springboot.common.entity.User;
import cn.qingfeng.demo.transaction.springboot.common.mapper.UserMapper;
import cn.qingfeng.demo.transaction.springboot.declarative.transactionSimple.service.TransactionalDemoService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
//@Transactional//可以用在类上或方法上，都用时以方法上的为准
public class TransactionalDemoServiceImpl2 implements TransactionalDemoService2 {//这里不要忘记实现接口，否则controller中注入不了。
    //注入用户Mapper
    @Autowired
    private UserMapper userMapper;

    /**
     * Transactional默认只对RuntimeException和Error生效，必检异常不会除法事务。
     * 如果必检异常也需要处罚事务，需要在Transactional注解中配置rollbackFor
     *
     * @throws Exception
     */
    @Transactional//(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void addUser2() throws Exception {
        User user = new User("fjlsdj", "jfodjgfdj");

        userMapper.add(user);
        System.out.println("向数据库中插入了User----" + user);

        int a = 1 / 0;//制造免检异常，验证事务回滚（如果没有事务，插入会成功。加了事务之后会回滚）
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public void testReadCommittedRead(){
        int id = 12;
        User user = userMapper.selectById(id);
        System.out.println("============"+user);
    }
}
